#include "Socket.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"
using namespace log_ns;

// using task_t=std::function<void()>;
using namespace socket_ns;
using command_service_t = std::function<void(SockSPtr, InetAddr &)>;
class TcpServer
{
public:
    TcpServer(command_service_t service ,uint16_t port = gport)
        : _port(port),
          _listensock(std::make_shared<TcpSocket>()),
          _isrunning(false),
          _service(service)


    {
        _listensock->BuildListenSocket(_port);
    }

    class ThreadDate
    {
    public:
        SockSPtr _sockfd;
        TcpServer *_self;
        InetAddr _addr;

    public:
        ThreadDate(SockSPtr sockfd, TcpServer *self, const InetAddr &addr) : _sockfd(sockfd), _self(self), _addr(addr)
        {
        }
    };
    void Loop()//
    {
        _isrunning = true;
        while (_isrunning)
        {
            InetAddr client;
            SockSPtr newsock = _listensock->Accepter(&client);
            if (newsock == nullptr)
                continue;
            LOG(INFO, "get a new link ,client info: %s,sockfd is :%d\n", client.AddrStr().c_str(), newsock->sockfd());
            // version2 ----多线程版本
            pthread_t tid;
            ThreadDate *td = new ThreadDate(newsock, this, client);
            pthread_create(&tid, nullptr, Execute, td);
        }
        _isrunning = false;
    }
    static void *Execute(void *args)
    {
        pthread_detach(pthread_self()); // 解除当前线程和父线程之间的联系
        ThreadDate *td = static_cast<ThreadDate *>(args);
        td->_self->_service(td->_sockfd, td->_addr);
        td->_sockfd->close();
        delete td;
        return nullptr;
    }

    ~TcpServer()
    {
    }

private:
    uint16_t _port;
    SockSPtr _listensock;
    bool _isrunning;
    command_service_t _service;//自定义的方法

};